<template>
  <div id="editorMDParentId" ref="md" style="height: 100%;">
    <div v-show="doType=='show'" id="show_html" class="show_note_html" v-html="content_html" @click="vHmtlClick" style="height: 100%;"/>
    <div v-show="doType=='editor'" id="editormdid" style="height: 100%;">
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import {getFileIcon,uploadFile,download} from '@/api/dl'

  export default {
    name: 'EditorMD',
    props: {
      content:{
        type: String,
        default: ''
      },
      content_html:{
        type: String,
        default: ''
      },
      doType: {
        type:String,
        default: 'show'
      },
      nnTextType: {//绑定云记的类型字段
        'type': Number, //
      },
      tableId:null,
    },
    data() {
      return {
        previewConfig:{
          img:["jpg", "jpeg", "gif", "png", "bmp"],
        },
        editorLoaded: false,
        instance: null,
        editorConfig:{
          width: "100%",
          height: "100%",
          path: '/lib/editor.md/lib/',
          markdown: '',      // 默认填充内容
          lineWrapping: true, // 编辑框不换行
          codeFold: true,                 // 代码折叠
          placeholder: '请输入...',
          syncScrolling: true,
          saveHTMLToTextarea: true,       // 保存 HTML 到 Textarea
          searchReplace: true,
          watch: true,                                // 实时预览
          htmlDecode: "style,script,iframe|yes*",      // 开启 HTML 标签解析，为了安全性，默认不开启
          toolbar: true,                  //工具栏
          previewCodeHighlight: true,     // 预览 HTML 的代码块高亮，默认开启
          emoji: true,
          taskList: true,
          tocm: true,                     // Using [TOCM]
          tocDropdown   : true,
          tocTitle      : "目录",
          imageUpload: true,
          imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"], //图片上传格式
          onload: function() {
            this.instance.config("tocDropdown", true);//加载完成后 配置生成目录
          },
          onchange : ()=>{
            if(this.doType=='editor'){
              this.$emit('change',this.instance.getPreviewedHTML(),this.instance.getMarkdown())
            }
          },
          /**
           *上传方法
           */
          uploadImage: (file,callback,progress)=>{
            let that=this;
            uploadFile(file,{
              tableId:that.tableId,
              workCode:1,
              objName:0
            },function (p,md5,o) {
                if(p==100){
                  if(callback)callback(Vue.prototype.webUrl+o.annexFile.saf_file_path);
                }
                progress(p);
            });
          }
        },
      };
    },
    mounted() {

    },
    created(){
      window.f_download=download;
    },
    /**
     * 属性状态监控
     */
    watch: {
      'content': {
        handler: function(){
            //渲染数据
        }
      },
      'content_html':{
        handler: function(){
          //渲染数据
        }
      },
      'doType': {
        handler: function(){
          if(this.doType=='editor'&&this.nnTextType==2){
            this.createEditorMd();
          }
        }
      }
    },
    methods: {
      /**
       * v-html单击事件监控
       * @param e
       */
      vHmtlClick(e){
        let className =e.target.className;
        if(className.indexOf("annexFile_a")!=-1){
          download(e.target.getAttribute("url"),e.target.getAttribute("fileName"));
        }
      },

      createEditorMd(){
        this.$nextTick(() => {
          let instance = window.editormd("editormdid", this.editorConfig);
          instance.on('load', () => {
            instance.setMarkdown(this.content);
          });
          this.instance = instance;
        });
      },
      insertValue(annex,type){
        let value="";
        if(type==1){//插入为预览
          let simg=new Set(this.previewConfig.img);
          if(simg.has(annex.annexFile.saf_file_type)){
            value= `<br/><img src="${Vue.prototype.webUrl+annex.annexFile.saf_file_path}" alt="${annex.sa_show_name}" title="${annex.sa_show_name}" />`;
          }
        }else{//2或其他插入为附件
          value= `<p><img src="/${getFileIcon(annex.annexFile.saf_file_type)}"><a class="annexFile_a" title="${annex.sa_show_name}"  url="${Vue.prototype.webUrl+annex.annexFile.saf_file_path}" fileName="${annex.sa_show_name}" target="_blank">${annex.sa_show_name}</a></p>`;
        }
        this.instance.insertValue(value);
      },
      //获取html
      toHtml(){
        var showdown  = require('showdown'),
                converter = new showdown.Converter(),
                text = this.content,
                html = converter.makeHtml(text);
        return html;
      },
    },
  };
</script>

<style scoped>
</style>